package com.shujia.day17.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        /*
            需求：从客户端发送一个文件数据到服务端，服务端对读取到的数据进行保存

            分析：
                1.创建socket对象
                2.通过socket对象创建输入流循环读取数据
                3.将读取到的数据通过IO流进行保存到本地　－＞字符流　－＞　BufferedWriter
                4.给客户端返回响应信息

         */

        ServerSocket serverSocket = new ServerSocket(7777);
        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();

        FileWriter fileWriter = new FileWriter("data/getTcp"+System.currentTimeMillis()+".txt");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);


        // 由于读取到的长度比较长，所以需要使用while循环不断进行读取数据
        byte[] bytes = new byte[1024];
        int read = 0;
        while ((read = inputStream.read(bytes))!= -1){
            String data = new String(bytes, 0, read);
            // 写出数据到本地
            bufferedWriter.write(data);
            bufferedWriter.flush();

        }
        socket.shutdownInput();

        // 给客户端返回响应信息
        OutputStream outputStream = socket.getOutputStream();

        outputStream.write("接收到文件".getBytes());
        outputStream.flush();

        bufferedWriter.close();
        socket.close();

    }
}
